package cn.graydove.bot.core;

import cn.graydove.bot.adapter.GroupMessageEvent;
import cn.graydove.bot.adapter.RobotClient;
import cn.graydove.bot.mirai.Client;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.regex.Pattern;

@Slf4j
public class Function {

    private Method method;

    private Object object;

    private Pattern[] regex;

    public Function(Method method, Object object, String[] regex) {
        this.method = method;
        this.object = object;
        int len = regex.length;
        this.regex = new Pattern[len];
        for (int i=0; i<len; ++i) {
            this.regex[i] = Pattern.compile(regex[i]);
        }
    }

    public boolean match(String text) {
        for (Pattern p: regex) {
            if (p.matcher(text).find()) {
                return true;
            }
        }
        return false;
    }

    public void invoke(Client client) {
        Type[] types = method.getGenericParameterTypes();
        int size = types.length;
        Object[] params = new Object[size];
        for (int i=0;i<size;++i) {
            if (Client.class.equals(types[i])) {
                params[i] = client;
            } else if (GroupMessageEvent.class.equals(types[i])) {
                params[i] = new GroupMessageEvent(client);
            } else if (RobotClient.class.equals(types[i])) {
                params[i] = new RobotClient(client);
            }
        }
        try {
            method.invoke(object, params);
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.error("方法调用失败");
        }
    }
}
